/**
 * inforcreation.com co.Ltd
 * MichaelHuang
 * 2011-12-16
 */
package com.zchat.android.receivers;

import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.zchat.api.connection.NetStatus;
import com.zchat.api.connection.NetType;
import com.zchat.api.connection.NetUtil;

/**
 * Recevier device's net change event.
 * @author MichaelHuang
 *
 */
public class DeviceNetStatusReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		//receive net work status and change the read status
		if(getCurrentState(context)) {
			//设置网络状态为可用状态
			NetUtil.getInstance().setNetStatus(context, NetStatus.avaliable);
		} else {
			//设置网络状态为不可用状态
			NetUtil.getInstance().setNetStatus(context, NetStatus.unavaliable);
		}
	}

	/**
	 * 获得当前网络状态
	 * @return false 网络不通 true通
	 * @author MichaelHuang
	 */
	public boolean getCurrentState(Context context) {
		ConnectivityManager connManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo currNetworkInfo = connManager.getActiveNetworkInfo();
		if(currNetworkInfo == null) {
			NetUtil.getInstance().setNetType(NetType.none);
//			Logger.debug("Net work has interrupted.");
			return false;
		} else {
//			Logger.debug("Net work has connected.");
			//set net type
			NetworkInfo mobileNetworkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);//判断GPRS、3G网络
			NetworkInfo wifiNetworkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);//判断wifi网络
			if(wifiNetworkInfo != null) {
				NetUtil.getInstance().setNetType(NetType.wifi);
			} else if(wifiNetworkInfo == null && mobileNetworkInfo != null) {
				NetUtil.getInstance().setNetType(NetType.mobile);
			}
			return true;
		}
		
	}
	
	public void register(Application application)
	{
		IntentFilter netFilter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
		application.registerReceiver(this, netFilter);
	}

}
